package com.zbu.test;

import java.util.Arrays;
import java.util.Scanner;

/**
 * 二分查找（折半查找）
 * 前提:数组必须有序
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] arr = {11,22,33,46,87,95,64,8,4,951,5,46};
        Arrays.sort(arr);
//        System.out.println(Arrays.toString(arr));
        int search;
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入要查找的元素:");
        search = sc.nextInt();
        System.out.println(search+"所在位置:"+(binarySearch(arr, search)+1));


    }

    private static int binarySearch(int[] arr, int search) {
        int min = 0,max= arr.length-1,mid;
        while (min<=max){
            mid= arr[(min+max)/2];
            if (mid==search){
                return (min+max)/2;
            } else if (mid>search) {
                max = (min+max)/2-1;
            } else{
                min = (min+max)/2+1;
            }
        }
        return -1;
    }
}
